#include <mutex>
#include "UserManager.h"
using namespace std;



UserManager::~UserManager()
{
}


bool UserManager::AddUser(std::string amonut, const TcpConnPtr& tcpPtr)
{	
	std::map<string, TcpConnPtr>::iterator it = _userConnptr.find(amonut);
	if (it == _userConnptr.end())
	{
		_userConnptr[amonut] = tcpPtr;	
		_fd2user[tcpPtr->channel_->fd()] = amonut;
	}
	return true;
}

bool UserManager::FindUser(std::string amonut, TcpConnPtr& tcpPtr)
{
	std::unique_lock<std::mutex> lck(_mtx);
	std::map<string, TcpConnPtr>::iterator it = _userConnptr.find(amonut);
	std::map<string, TcpConnPtr>::iterator iter = _userConnptr.begin();
	for (iter = _userConnptr.begin(); iter != _userConnptr.end(); iter++)
	{			
		trace("user in map %s\n", iter->first.c_str());
	}
	if (it == _userConnptr.end())
	{
		return false;
	}
	tcpPtr = _userConnptr[amonut];
	return true;
}

bool UserManager::RemoveUser(const TcpConnPtr& tcpPtr)
{
	std::unique_lock<std::mutex> lck(_mtx);
	std::map<int, string>::iterator it = _fd2user.find(tcpPtr->channel_->fd());
	if (it != _fd2user.end())
	{
		std::string amount = _fd2user[tcpPtr->channel_->fd()];
		std::map<string, TcpConnPtr>::iterator itr = _userConnptr.find(amount);
		if (itr == _userConnptr.end())
		{
			return false;
		}
		_userConnptr.erase(amount);
	}
	else
		return false;
	return true;
}
